package com.threeox.commonlibrary.impl;

import com.threeox.commonlibrary.inter.navigation.INavigationMsg;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.PinyinUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 
 * @ClassName: PinyinNavigationComparator
 * 
 * @Description: TODO(检索排序)
 * 
 * @author 赵屈犇
 * 
 * @date 创建时间: 2017/8/16 16:26
 * 
 * @version 1.0
 * 
 */
public class PinyinNavigationComparator implements Comparator<INavigationMsg> {

    private PinyinNavigationComparator() {}

    public static PinyinNavigationComparator newInstance() {
        return new PinyinNavigationComparator();
    }

    public int compare(INavigationMsg o1, INavigationMsg o2) {
        if (EmptyUtils.isEmpty(o1.getNavigationValue()) || EmptyUtils.isEmpty(o1.getNavigationValue())) {
            return -1;
        }
        if ("@".equals(o1.getNavigationValue()) || "#".equals(o2.getNavigationValue())) {
            return -1;
        } else if ("#".equals(o1.getNavigationValue()) || "@".equals(o2.getNavigationValue())) {
            return 1;
        } else {
            return o1.getNavigationValue().compareTo(o2.getNavigationValue());
        }
    }

    /**
     * 转换导航对象
     *
     * @param datas 数据
     * @param fieldName 字段名称
     * @return
     */
    public <T extends List> T switchNavigationMsg(List datas, String fieldName) {
        List<INavigationMsg> navigationMsgs = new ArrayList<INavigationMsg>();
        for (Object data : datas) {
            if (data instanceof INavigationMsg) {
                INavigationMsg navigationMsg = (INavigationMsg) data;
                try {
                    Field field = data.getClass().getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object fieldValue = field.get(data);
                    if (EmptyUtils.isNotEmpty(fieldValue)) {
                        String sortString = PinyinUtils.getPinyinFirstLetter(String.valueOf(fieldValue)).toUpperCase();
                        // 正则表达式，判断首字母是否是英文字母
                        if (sortString.matches("[A-Z]")) {
                            navigationMsg.setNavigationValue(sortString);
                        } else {
                            navigationMsg.setNavigationValue("#");
                        }
                    } else {
                        navigationMsg.setNavigationValue("#");
                    }
                } catch (Exception e) {
                    navigationMsg.setNavigationValue("#");
                }
                navigationMsgs.add(navigationMsg);
            }
        }
        // 根据a-z进行排序
        Collections.sort(navigationMsgs, this);
        return (T) navigationMsgs;
    }

}
